package com.sogoodsoft.web.sys;

import java.io.File;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.opensymphony.xwork2.ActionSupport;
import com.sogoodsoft.util.DwzMsg;
import com.sogoodsoft.util.InfosysUtils;
import com.sogoodsoft.web.WebConstants;

@SuppressWarnings("serial")
public class BackdbAction extends ActionSupport {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String dir = WebConstants.DBDIR;

    private String cmd = "";

    private String name = "";

    private String password = "";

    String path = "";

    public String execute() throws Exception {
        boolean success = true;

        initConfig();
        if(WebConstants.mysql){
        	success = mysql();
        }else{
        	success = oracle();
        }
      
        if (success) {
            DwzMsg msg = new DwzMsg();
            msg.message = "备份成功！<br>文件存放路径：" + path;
            msg.statusCode = DwzMsg.STATUS.SUCCESS;
            Struts2Utils.renderJson(msg.msg());
        }
        return null;
    }
    
    public boolean  mysql(){
    	boolean success = false;
   	 	path = InfosysUtils.translatePath(dir + File.separator + "sogoodsoft" + InfosysUtils.getNow() + ".sql");
        
        cmd = "mysqldump -u" + name + " -p" + password + " sogoodsoft -r" + path;
        try {
            success = InfosysUtils.exec(cmd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.debug("执行备份命令：" + cmd);
        return success;
    }
    
    public boolean oracle(){
    	boolean success = false;
    	 path = InfosysUtils.translatePath(dir + File.separator + "sogoodsoft" + InfosysUtils.getNow() + ".dmp");
         
         cmd = "exp " + name + "/" + password + " file=" + path;
         try {
             success = InfosysUtils.exec(cmd);
         } catch (Exception e) {
             e.printStackTrace();
         }
         logger.debug("执行备份命令：" + cmd);
         return success;
    }
    

    public String input() throws Exception {
        return INPUT;
    }

    public void initConfig() throws Exception {
        Properties props = PropertiesLoaderUtils.loadAllProperties("application.properties");
        name = props.getProperty("jdbc.username");
        password = props.getProperty("jdbc.password");
        logger.debug("name=" + name + " " + "password=" + password);
    }
}
